#!/bin/bash

set -e
API_URL="http://localhost:8003/api"

fail_exit() {
  echo "[ERROR] $1"
  exit 1
}

echo "== 创建用户 =="
USER_CREATE_RESP=$(curl -s -w "%{http_code}" -X POST "$API_URL/users" \
  -H "Content-Type: application/json" \
  -d '{"name":"TestUser","email":"test@example.com","age":30,"phone":"1234567890"}')
USER_CREATE_CODE=${USER_CREATE_RESP: -3}
if [ "$USER_CREATE_CODE" != "200" ] && [ "$USER_CREATE_CODE" != "201" ]; then
  fail_exit "创建用户失败: $USER_CREATE_RESP"
fi

USER_ID=$(curl -s "$API_URL/users" | jq '.[-1].id')
echo "USER_ID: $USER_ID"

if [ -z "$USER_ID" ] || [ "$USER_ID" == "null" ]; then
  fail_exit "获取用户ID失败"
fi

echo "== 创建订单 =="
ORDER_CREATE_RESP=$(curl -s -w "%{http_code}" -X POST "$API_URL/orders" \
  -H "Content-Type: application/json" \
  -d "{\"userId\":$USER_ID,\"totalAmount\":99.99,\"createTime\":\"2024-06-25T10:00:00\",\"status\":\"NEW\"}")
ORDER_CREATE_CODE=${ORDER_CREATE_RESP: -3}
if [ "$ORDER_CREATE_CODE" != "200" ] && [ "$ORDER_CREATE_CODE" != "201" ]; then
  fail_exit "创建订单失败: $ORDER_CREATE_RESP"
fi

ORDER_ID=$(curl -s "$API_URL/orders" | jq '.[-1].id')
echo "ORDER_ID: $ORDER_ID"

if [ -z "$ORDER_ID" ] || [ "$ORDER_ID" == "null" ]; then
  fail_exit "获取订单ID失败"
fi

echo "== 查询订单 =="
ORDER_GET_RESP=$(curl -s -w "%{http_code}" "$API_URL/orders/$ORDER_ID")
ORDER_GET_CODE=${ORDER_GET_RESP: -3}
if [ "$ORDER_GET_CODE" != "200" ]; then
  fail_exit "查询订单失败: $ORDER_GET_RESP"
fi

echo "== 查询所有订单 =="
curl -s "$API_URL/orders" | jq

echo "== 更新订单 =="
ORDER_UPDATE_RESP=$(curl -s -w "%{http_code}" -X PUT "$API_URL/orders/$ORDER_ID" \
  -H "Content-Type: application/json" \
  -d "{\"id\":$ORDER_ID,\"userId\":$USER_ID,\"totalAmount\":199.99,\"createTime\":\"2024-06-25T10:00:00\",\"status\":\"PAID\"}")
ORDER_UPDATE_CODE=${ORDER_UPDATE_RESP: -3}
if [ "$ORDER_UPDATE_CODE" != "200" ]; then
  fail_exit "更新订单失败: $ORDER_UPDATE_RESP"
fi

echo "== 查询用户订单 =="
curl -s "$API_URL/orders/user/$USER_ID" | jq

echo "== 删除订单 =="
ORDER_DELETE_RESP=$(curl -s -w "%{http_code}" -X DELETE "$API_URL/orders/$ORDER_ID")
ORDER_DELETE_CODE=${ORDER_DELETE_RESP: -3}
if [ "$ORDER_DELETE_CODE" != "200" ]; then
  fail_exit "删除订单失败: $ORDER_DELETE_RESP"
fi

echo "== 验证订单已删除 =="
ORDER_CHECK_RESP=$(curl -s -w "%{http_code}" "$API_URL/orders/$ORDER_ID")
ORDER_CHECK_CODE=${ORDER_CHECK_RESP: -3}
if [ "$ORDER_CHECK_CODE" == "200" ]; then
  fail_exit "订单未被删除: $ORDER_CHECK_RESP"
fi

echo "所有接口测试通过！"